package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  true,        // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	////db.AutoMigrate(&User{})

	var users = []User{{Name: "james"}, {Name: "john"}, {Name: "jareo"}}
	db.Create(&users)
	for _, user := range users {
		fmt.Println("user id:", user.ID)
	}

	users = []User{{Name: "李白"}, {Name: "辛弃疾"}, {Name: "杜甫"}}
	// 数量为 2,SQL语句是有长度限制的
	db.CreateInBatches(users, 2)

	//根据Map创建
	db.Model(&User{}).Create(map[string]interface{}{
		"Name": "灭霸", "Age": 100,
	})

}
